package cn.edu.sgu.www.mhxysy.service.except.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.observer.impl.AdvancedPropertyObserver;
import cn.edu.sgu.www.mhxysy.subject.impl.AdvancedPropertySubject;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.service.except.AdvancedPropertyService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class AdvancedPropertyServiceImpl implements AdvancedPropertyService {

    private final RedisUtils redisUtils;
    private final AdvancedPropertySubject advancedPropertySubject;
    private final AdvancedPropertyObserver advancedPropertyObserver;

    @Autowired
    public AdvancedPropertyServiceImpl(
            RedisUtils redisUtils,
            AdvancedPropertySubject advancedPropertySubject,
            AdvancedPropertyObserver advancedPropertyObserver) {
        this.redisUtils = redisUtils;
        this.advancedPropertySubject = advancedPropertySubject;
        this.advancedPropertyObserver = advancedPropertyObserver;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Integer> selectByRoleId(String roleId) {
        String key = RedisKeyPrefixes.PREFIX_ADVANCED_PROPERTY + roleId;

        // 没有命中缓存
        if (!redisUtils.hasKey(key)) {
            advancedPropertySubject.addObserver(advancedPropertyObserver);
            advancedPropertySubject.notice(roleId);
        }

        String data = redisUtils.get(key);

        return JSON.parseObject(data, Map.class);
    }

}